package com.yunji.hushuang.dynamicproxy;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 自定义类装载器，通过流读取 class 文件
 *
 * @author hushuang
 * @since 2019/10/14
 */
public class MyClassLoader extends ClassLoader {

    private File classFilePath;

    public MyClassLoader() {
        this.classFilePath = new File(MyClassLoader.class.getResource("").getPath());
    }

    /**
     * 通过流读取 class 文件，调用 defineClass 装载
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = MyClassLoader.class.getPackage().getName() + "." + name;
        try (FileInputStream fis = new FileInputStream(new File(classFilePath, name + ".class"));
             ByteOutputStream bos = new ByteOutputStream()) {
            bos.write(fis);
            return defineClass(className, bos.getBytes(), 0, bos.getCount());
        } catch (IOException e) {
            throw new ClassNotFoundException("class " + className + " not found", e);
        }
    }
}
